package Others.Canal.config;


import Others.Canal.properties.SourceDbProperties;
import Others.Canal.properties.TargetDbProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;


@EnableConfigurationProperties({SourceDbProperties.class, TargetDbProperties.class})
public class JdbcConfig {

    @Autowired
    private TargetDbProperties targetDbProperties;

    @Autowired
    private SourceDbProperties sourceDbProperties;

    /**
     * 创建目标数据库的JDBC模板（用于写入同步数据）
     */
    @Bean("targetJdbcTemplate")
    public JdbcTemplate targetJdbcTemplate() {
        DriverManagerDataSource targetDataSource = new DriverManagerDataSource();
        targetDataSource.setDriverClassName(targetDbProperties.getTARGET_DB_DRIVER_CLASS_NAME());
        targetDataSource.setUrl(targetDbProperties.getTARGET_DB_URL());
        targetDataSource.setUsername(targetDbProperties.getTARGET_DB_USERNAME());
        targetDataSource.setPassword(targetDbProperties.getTARGET_DB_PASSWORD());
        return new JdbcTemplate(targetDataSource);
    }

    /**
     * 创建源数据库的JDBC模板（用于全量同步）
     */
    @Bean("sourceJdbcTemplate")
    public JdbcTemplate sourceJdbcTemplate() {
        DriverManagerDataSource sourceDataSource = new DriverManagerDataSource();
        sourceDataSource.setDriverClassName(sourceDbProperties.getSOURCE_DB_DRIVER_CLASS_NAME());
        sourceDataSource.setUrl(sourceDbProperties.getSOURCE_DB_URL());
        sourceDataSource.setUsername(sourceDbProperties.getSOURCE_DB_USERNAME());
        sourceDataSource.setPassword(sourceDbProperties.getSOURCE_DB_PASSWORD());
        return new JdbcTemplate(sourceDataSource);
    }

    /**
     * 创建状态数据库的JDBC模板（用于记录同步状态）
     * 注意：这里复用了目标数据库来存储同步状态
     */
    @Bean("statusJdbcTemplate")
    public JdbcTemplate statusJdbcTemplate(@Autowired @Qualifier("targetJdbcTemplate") JdbcTemplate targetJdbcTemplate) {
        return targetJdbcTemplate;
    }

}
